<template>
  <div class="user-component">
    <el-input v-model="formData.checkData" readonly>
      <span v-if="!readonly && !formData.checkData" slot="suffix" class="el-icon-user-solid input-icon" @click="dialogVisible = true"></span>
      <span v-if="!readonly && formData.checkData" class="el-icon-close input-icon" slot="suffix" @click="reset"></span>
    </el-input>
    <CustomActionSheet :modelValue="dialogVisible" title="选择人员" confirm-text="确认" cancel-text="取消" @confirm="confirmUser" @cancel="handleClose" :showFooter="true">
      <template #content>
        <div>
          <p>已选人员：{{choosObj.userName}}</p>
          <div class="user-box">
            <!-- <van-search v-model="tempKeyword" placeholder="请输入模板名称或编码" @search="onTempSearch" class="search-bar" /> -->
            <el-tree ref="deptTree" :props="defaultProps" :data="deptTreeData" @check="handleDeptNodeClick" default-expand-all check-strictly show-checkbox node-key="departmentId" > </el-tree>
          </div>
        </div>
      </template>
    </CustomActionSheet>
     <CustomActionSheet :modelValue="userShow" title="人员明细" confirm-text="确认" cancel-text="取消"  @confirm="confirm" @cancel="handleCloseUser" :showFooter="true">
      <template #content>
        <div>
          <div class="user-box" v-if="userList.length>0">
           <el-tree
             ref="userTree"
                  :data="userList"
                  node-key="userId"
                  check-strictly
                  show-checkbox
                  @check="handleUserNodeClick"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <div @dblclick="handleToRight(data)" class="user-info">
                      <div class="user-info-name">{{ data.userName }}</div>
                      <div class="user-info-post">{{ data.postName }}</div>
                    </div>
                  </span>
                </el-tree>
          </div>
          <!-- <div v-else>
                 <van-empty  description="暂无数据" />
          </div> -->
         
        </div>
      </template>
    </CustomActionSheet>
  </div>
</template>
<script>
import globalService from '@/services/globalService'
import eventBus from '@/assets/utils/eventBus.js'
import CustomActionSheet from '@/components/CustomActionSheet.vue'
import { Toast } from 'vant';
export default {
  name: 'userComponent',
  components: {
    CustomActionSheet
  },
  props: {
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    value: [Object, String],
    disabled: Boolean,
    parameter: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      formData: {},
      dialogVisible: false,
      userShow:false,
      activeName: '1',
      searchText: '',
      userList: [],
      deptTreeData: [],
      defaultProps: {
        label: 'departmentName',
        children: 'departmentInfos',
        isLeaf: 'leaf'
      },
      currentDeptNodeKey: null, // 部门选中节点
      departmentFullPath: null, // 部门全路径
      currentUserNodeKey: null, // 人员选中节点
      chooseData: [], // 已选择的人员信息
      choosObj: {},
      readonly: false,
      userCode: localStorage.getItem('userCode')
    }
  },
  watch: {
    dialogVisible: function (val) {
      console.log('[ val ]-152', val)
      if (val) {
        this.queryDeptTree()
      }
    }
  },
  created() {
    this.readonly = Boolean(this.$route.query.readonly) || this.disabled
    if (this.value) {
      this.setData()
    }
    // 展示当前登录人默认选中
    if (!this.readonly && this.userCode && !this.formData.checkData) {
      this.queryDeptStaffList()
    }
  },
  methods: {
    loadNode(node, resolve) {
        console.log('[ node ]-86', node.level)
        if (node.level === 0) {
          // return resolve([{ name: 'region' }]);
        }
        // if (node.level > 1) return resolve([]);

        // setTimeout(() => {
        //   const data = [{
        //     name: 'leaf',
        //     leaf: true
        //   }, {
        //     name: 'zone'
        //   }];

        //   resolve(data);
        // }, 500);
      },
    queryDeptStaffList() {
      globalService
        .queryDeptStaffList({
          userCode: this.userCode
        })
        .then((res) => {
          const data = res.data || []
          const info = data[0] || {}
          this.getData(info)
        })
    },
    queryDeptTree() {
      globalService.queryDeptTree({}).then((res) => {
        this.deptTreeData = res.data || []
        // 递归处理部门树，为叶子节点添加isLeaf属性
        // const addIsLeafProperty = (nodes) => {
        //   nodes.forEach(node => {
        //     if (!node.departmentInfos || node.departmentInfos.length === 0) {
        //       node.isLeaf = true;
        //     } else {
        //       addIsLeafProperty(node.departmentInfos);
        //     }
        //   });
        // };
        // addIsLeafProperty(this.deptTreeData);
        if (this.formData.departmentId) {
          this.currentDeptNodeKey = this.formData.departmentId
          this.departmentFullPath = this.formData.departmentFullPath
          this.currentUserNodeKey = this.formData.userId
          this.queryData()
          this.choosObj = { ...this.formData }
          this.chooseData = [{ ...this.formData }]
        }
        this.setCheckedKeys('dept')
      })
    },
    // 部门树
    handleDeptNodeClick(data) {
      this.departmentFullPath = data.path
      // 更新当前选中节点的 key
      this.currentDeptNodeKey = data.departmentId
      this.setCheckedKeys('dept')
      // 查询人员信息
      this.queryData()
      // 更新选择人员节点信息
      this.currentUserNodeKey = null
    },
    queryData() {
      if (!this.departmentFullPath) {
        this.$message.warning(this.$t('请先选择部门'))
        return
      }
      globalService
        .queryDeptStaffList({
          path: this.departmentFullPath,
          userName: this.searchText
        })
        .then((res) => {
          this.userList = res.data || []
          this.userShow = true
          console.log('[  this.userShow ]-193',  this.userShow)
          this.setCheckedKeys('user')
          
        })
    },
    // 人员树
    handleUserNodeClick(data) {
      // 更新当前选中节点的 key
      this.currentUserNodeKey = data.userId
      // 选中的节点信息
      this.choosObj = data
      this.handleToRight(data)
      this.setCheckedKeys('user')
    },
    setCheckedKeys(type) {
      switch (type) {
        case 'dept':
          if (this.currentDeptNodeKey && this.$refs.deptTree) {
            // 更新当前选中节点的 key
            this.$refs.deptTree.setCheckedKeys([this.currentDeptNodeKey])
          }
          break
        case 'user':
          if (this.currentUserNodeKey && this.$refs.userTree) {
            // 更新当前选中节点的 key
            this.$refs.userTree.setCheckedKeys([this.currentUserNodeKey])
          }
          break
      }
    },
    handleToRight(data) {
      this.chooseData = [{ ...data }]
    },
    handleOnRight() {
      if (this.choosObj && this.choosObj.userId) {
        this.chooseData = [{ ...this.choosObj }]
      } else {
        this.$message.warning(this.$t('请选择人员'))
      }
    },
    handleToLeft(data) {
      this.chooseData = []
    },
    handleClose() {
      this.dialogVisible = false
      this.deptTreeData = []
      this.userList = []
      this.currentDeptNodeKey = null
      this.currentUserNodeKey = null
      this.chooseData = []
      this.choosObj = {}
      this.userShow = false
      this.formData = {}
    },
    confirm() {
      if (this.chooseData && this.chooseData.length) {
        const data = this.chooseData[0]
        this.getData(data)
        // this.handleClose()
        this.userShow = false
        this.$emit('changeRule')
      } else {
        Toast(this.$t('请选择人员'))
      }
    },
    handleCloseUser(){
      this.userShow = false
      this.choosObj = {}
    },
    confirmUser(){
      this.dialogVisible = false
    },
    // 回显信息
    getData(data) {
      // 1展示人员姓名 2展示人员姓名和工号
      const displayType = this.parameter?.parameterValue?.displayType
      this.formData = {
        ...data,
        checkData: data.userName
      }
      if (displayType == 2) {
        this.$set(this.formData, 'checkData', `${data.userName}-${data.userCode}`)
      }
      const params = {
        value: this.formData.checkData,
        selectData: this.formData
      }
      this.$emit('input', JSON.stringify(params))
    },
    reset() {
      this.formData = {}
      this.$emit('input', '')
      this.$emit('changeRule')
    },
    setData() {
      let data = JSON.parse(this.value)
      this.formData = {
        ...data.selectData
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.input-icon {
  cursor: pointer;
}
::v-deep .el-dialog__body {
  padding-top: 0px;
}
.user-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  height: 80vh;
  &-left {
    width: 62%;
    display: flex;
    &-item {
      width: 50%;
    }
  }
  &-right {
    width: 31%;
  }
  &-center {
    display: flex;
    justify-content: center;
    align-items: center;
    .right-arrow {
      cursor: pointer;
    }
  }
  &-item {
    border: 1px solid #c6ccd0;
    background: #fff;
    height: 100%;
    max-height: 550px;
    overflow: hidden;
    &-header {
      background: #f8f8f8;
      height: 45px;
      padding: 5px 10px;
      box-sizing: border-box;
    }
    &-content {
      padding: 10px;
      box-sizing: border-box;
      max-height: 500px;
      overflow: auto;
      .custom-tree-node {
        width: 100%;
      }
      .user-info {
        width: 100%;
        display: flex;
        justify-content: space-between;
        &-name {
          //max-width: 200px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &-post {
          //ax-width: 110px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
  .user-box-left-item:first-child {
    border-right: 0 none;
  }
}
 .user-info {
        width: 100%;
        display: flex;
        justify-content: space-between;
        &-name {
          max-width: 200px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &-post {
          max-width: 110px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
</style>
yle>
